# 公用的工具类
import functools

from flask import current_app
from flask import g
from flask import session

from info.models import User


# 自定义过滤器--根据下标返回不同类属性
def do_index_class(index):
    if index == 0:
        return 'first'
    elif index == 1:
        return 'second'
    elif index == 2:
        return 'third'
    return ''


# 自定义过滤器--根据下标判断是否返回‘active‘类属性
def do_index_active(index):
    if index == 0:
        return 'active'
    return ''


# 装饰器处理每个页面的登录信息
def login_data(f):
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        # 根据session中存储的user_id查询数据库中的头像，昵称
        user_id = session.get('user_id', None)
        user = None
        if user_id:
            try:
                user = User.query.get(user_id)
            except Exception as e:
                current_app.logger.error(e)
        g.user = user
        return f(*args, **kwargs)
    return wrapper
